package com.lianboke.link.ad.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lianboke.link.ad.R;
import com.lianboke.link.ad.VolleyUtils.HttpCallBack;
import com.lianboke.link.ad.VolleyUtils.HttpUtil;
import com.lianboke.link.ad.bankmodelinfo.BankModel;
import com.lianboke.link.ad.bankmodelinfo.BankModelInfo;
import com.lianboke.link.ad.bankmodelinfo.BankPopupWindow;
import com.lianboke.link.ad.common.CommonParams;
import com.lianboke.link.ad.utils.DeviceUtils;
import com.lianboke.link.ad.utils.KLog;
import com.lianboke.link.ad.utils.MobclickAgentUtils;
import com.lianboke.link.ad.utils.ToastUtil;
import com.lianboke.link.ad.utils.Validator;

import org.json.JSONObject;

import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 注册页面
 */
public class RegisterActivity extends BaseActivity {

    @BindView(R.id.et_phone)
    public EditText et_phone;

    @BindView(R.id.et_qq)
    public EditText et_qq;

    @BindView(R.id.et_email)
    public EditText et_email;

    @BindView(R.id.et_zfb_name)
    public EditText et_zfb_name;

    @BindView(R.id.et_zfb_account)
    public EditText et_zfb_account;

    @BindView(R.id.et_bank_name)
    public EditText et_bank_name;

    @BindView(R.id.et_bank_address)
    public EditText et_bank_address;
    @BindView(R.id.et_bank_card)
    public EditText et_bank_card;

    @BindView(R.id.btn_register_submit)
    public Button btn_register_submit;

    @BindView(R.id.register_progress)
    public ProgressBar register_progress;

//    public MyRegisterHandler myRegisterHandler;
    private List<BankModel> mBankDatas;//银行信息
    public String bankAddressName;
    private String strBankCode;//银行

    @Override
    public int getContentViewId() {
        return R.layout.activity_register;
    }

    @Override
    public void initActivityParams(Bundle savedInstanceState) {
        setTitleBackShow(false);
        setTitleContent("注册");
        btn_register_submit.setOnClickListener(
                new View.OnClickListener(){
                    @Override
                    public void onClick(View view) {
                        checkRegisterValue();
                    }
                }
        );
        //初始化
        initBankInfoData();
        initPopupWindow();
    }
    public void gotoLoginctiviy(){
        Intent mIntent = new Intent();
        mIntent.setClass(RegisterActivity.this,LoginActivity.class);
        startActivity(mIntent);
        finish();
    }

    private String getValueById(EditText editText){
        return editText.getText().toString().trim();
    }
    private void checkViewValue(String value,String content){
        if(TextUtils.isEmpty(value)){
            hideRegisterProgress();
            ToastUtil.showShort(actContext,content);
            return;
        }
    }
    private void showRegisterProgress(){
        if(register_progress!=null && register_progress.getVisibility()!=View.VISIBLE){
            register_progress.setVisibility(View.VISIBLE);
        }
    }
    private void hideRegisterProgress(){
        if(register_progress!=null && register_progress.getVisibility()!=View.GONE){
            register_progress.setVisibility(View.GONE);
        }
    }
    /**
     * 检查数据
     */
    public void checkRegisterValue(){
        showRegisterProgress();
        String strUserPhone = getValueById(et_phone);
        checkViewValue(strUserPhone,"电话号码不能为空");
        if(!Validator.isMobile(strUserPhone)){
            ToastUtil.showShort(actContext,"请输入正确手机号");
            hideRegisterProgress();
            return;
        }

        String strUserQQ= getValueById(et_qq);

        String strUserEmail = getValueById(et_email);
        if(!TextUtils.isEmpty(strUserEmail)){
            if(!Validator.isEmail(strUserEmail)){
                ToastUtil.showShort(actContext,"请输入正确邮箱地址");
                hideRegisterProgress();
                return;
            }
        }
        String strUserZFBName = getValueById(et_zfb_name);
        checkViewValue(strUserZFBName,"请输入支付宝认证姓名不能为空");
        String strUserZFBAccount = getValueById(et_zfb_account);
        checkViewValue(strUserZFBAccount,"请输入支付宝认证账号");


        String strBankCard = getValueById(et_bank_card);
        checkViewValue(strBankCard,"请输入银行卡卡号信息");
        String strBankAddress = getValueById(et_bank_address);
        checkViewValue(strBankAddress,"请选择所属银行");
        String strAccountname = getValueById(et_bank_name);
        checkViewValue(strAccountname,"请输入持卡人姓名");

        HashMap<String,String> params = new HashMap<String,String>();
        params.put("phone",strUserPhone);
        params.put("qq",strUserQQ);
        params.put("email",strUserEmail);
        params.put("zhifubaorealname",strUserZFBName);
        params.put("zhifubaoaccount",strUserZFBAccount);
        params.put("deviceid", DeviceUtils.getImei(actContext));
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("bankcard",strBankCard);//卡号
        params.put("bankadress",bankAddressName);//开户行
        params.put("bankaccountname",strAccountname);//持卡人姓名
        params.put("bankcode",strBankCode);//银行code

        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_REGISTER, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String content) {
                hideRegisterProgress();
                int resultData = getRegisterData(content);
                if(resultData==1){
                    //跳转到登陆
                    gotoLoginctiviy();
                }else{
                    String msg = "";
                    try{
                        JSONObject jsonObject = new JSONObject(content);
                        msg = jsonObject.optString("m");

                    }catch (Exception e){

                    }
                    if(TextUtils.isEmpty(msg)){
                        msg = "注册失败";
                    }
                    MobclickAgentUtils.UmengRegisterEvent(appContext,params,11);
                    ToastUtil.showShort(actContext,msg);
                }
            }

            @Override
            public void onFail(String msg) {
                hideRegisterProgress();
                if(TextUtils.isEmpty(msg)){
                    msg = "注册失败";
                }
                MobclickAgentUtils.UmengRegisterEvent(appContext,params,12);
                ToastUtil.showShort(actContext,msg);
            }
        });
    }

    //===============================数据解析=======================================
    public static int getRegisterData(String content){
        int result = -1;
        if(!TextUtils.isEmpty(content)){
            Gson gson=new Gson();
            List<String> rs=new ArrayList<String>();
            Type type = new TypeToken<ArrayList<String>>() {}.getType();
            rs=gson.fromJson(content, type);
            if(rs!=null && !rs.isEmpty()){
                KLog.e("------------------gson:"+rs.get(0));
                result= Integer.valueOf(rs.get(0));
            }
        }
        KLog.e("--------result----------gson:"+result);
        return result;
    }

//===================银行卡===============================
    /**
     * 初始化数据
     */
    private void initBankInfoData() {
        try {
           InputStream is = getAssets().open("bankInfo.json");
            int length = is.available();
            byte[] buffer = new byte[length];
            is.read(buffer);
            String result =new String(buffer, "utf8");
            Gson gson = new Gson();
            mBankDatas = gson.fromJson(result, BankModelInfo.class).data;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化银行框
     */
    private void initPopupWindow() {
        final BankPopupWindow popupWindow = new BankPopupWindow(this);
        popupWindow.setOnBankSelectListener(new BankPopupWindow.OnBankSelectListener() {
            @Override
            public void onBankSelect(BankModel model) {
                if (model == null) return;
                et_bank_address.setText(model.getName());
                bankAddressName = model.getName();
                strBankCode = model.getCode();
            }
        });
        et_bank_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.setData(mBankDatas);
                popupWindow.show();
            }
        });
    }

}
